<template>
  <div class="index">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <div style="margin-top: 15px;">
      <el-input placeholder="请输入内容"
                v-model="query"
                class="input-with-select"
                style="width:300px; margin-right: 15px"
                @keyup.enter.native="seach">
        <el-button slot="append"
                   icon="el-icon-search"
                   @click="seach"></el-button>
      </el-input>
      <el-button type="primary"
                 round
                 @click="dialogFormVisible=true">添加用户</el-button>
    </div>
    <!-- 表格区域 -->
    <el-table :data="userList"
              border
              style="width: 100%; margin-top: 10px ">
      <el-table-column label="序号"
                       type="index"
                       width="50">
      </el-table-column>
      <el-table-column prop="username"
                       label="姓名"
                       width="180">
      </el-table-column>
      <el-table-column prop="email"
                       label="邮箱"
                       width="180">
      </el-table-column>
      <el-table-column prop="mobile"
                       label="电话">
      </el-table-column>
      <el-table-column label="用户状态"
                       width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state"
                     active-color="#13ce66"
                     inactive-color="#ff4949"
                     @change="changeUserState(scope.row.id,scope.row.mg_state)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item"
                      effect="dark"
                      content="编辑"
                      placement="top">

            <el-button type="primary"
                       icon="el-icon-edit"
                       @click="editUser(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item"
                      effect="dark"
                      content="分配角色"
                      placement="top">
            <el-button type="primary"
                       icon="el-icon-share"
                       @click="showGrandDialong(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item"
                      effect="dark"
                      content="删除"
                      placement="top">
            <el-button type="primary"
                       icon="el-icon-delete"
                       @click="delUser(scope.row.id)">
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pagenum"
                     :page-sizes="[1,2,3,4,5]"
                     :page-size="pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!-- 弹框 -->
    <el-dialog title="添加用户"
               :visible.sync="dialogFormVisible">
      <el-form :model="addForm"
               :label-width="'180px'"
               :rules="rules"
               ref="addForm">
        <el-form-item label="用户名"
                      prop="username"
                      disabled=""
                     >
          <el-input v-model="addForm.username"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addForm.email"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="mobile">
          <el-input v-model="addForm.mobile"
                    auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色"
               :visible.sync="dialogFormVisibleUserRole">
      <el-form :model="grantForm"
               label-width="120px"
               style="text-align: left">
        <el-form-item label="用户名">
          <el-input v-model="grantForm.username"
                    auto-complete="off"
                    disabled=""
                    style="width:100px"></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="grantForm.rid"
                     placeholder="请选择"
                     @change="roleSelect">
            <el-option v-for="item in roleList"
                       :key="item.id"
                       :label="item.roleName"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisibleUserRole = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUserRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="用户编辑"
               :visible.sync="editDialogFormVisible">
      <el-form :model="editForm"
               :label-width="'120px'"
               :rules="rules"
               ref="editForm">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="editForm.username"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"
                    auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="mobile">
          <el-input v-model="editForm.mobile"
                    auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editUserSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsersList, addUser, deleteUser, updateUserState, grantUserRole, editUser } from '@/api/users_api.js'
import { getRoleAllList } from '@/api/role_api.js'
export default {
  data () {
    return {
      editDialogFormVisible: false,
      dialogFormVisible: false,
      dialogFormVisibleUserRole: false,
      roleList: {},
      editForm: {
        id: '',
        email: '',
        mobile: '',
        username: ''
      },
      // 添加用户对象
      addForm: {
        username: '',
        password: '',
        email: '4455@163.com',
        mobile: '13556604444'
      },
      grantForm: {
        username: '',
        rid: '',
        id: ''
      },
      // 用户搜素关键字
      query: '',
      pagenum: 1,
      pagesize: 5,
      total: 0,
      userList: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur', pattern: /\w+[@]\w+[.]\w{2,3}/ }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur', pattern: /^1[345678]\d{9}$/ }
        ]
      }
    }
  },
  mounted () {
    this.init()
    getRoleAllList()
      .then((res) => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          this.roleList = res.data.data
        }
      })
      .catch((err) => {
        console.log(err)
      })
  },
  methods: {
    seach () {
      this.pagenum = 1
      this.init()
    },
    // 数据初始化
    init () {
      getUsersList({ query: this.query, pagenum: this.pagenum, pagesize: this.pagesize })
        .then((res) => {
          // console.log(res)
          this.userList = res.data.data.users
          this.total = res.data.data.total
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.init()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.init()
    },
    // 添加用户
    addUser () {
      // 1. 验证表单
      this.$refs.addForm.validate((valid) => {
        // 2.调用方法
        if (valid) {
          addUser(this.addForm)
            .then((res) => {
              // console.log(res)
              if (res.data.meta.status === 201) {
                this.dialogFormVisible = false
                // 重置表但数据
                this.$refs.addForm.resetFields()
                this.init()
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    },
    // 删除
    delUser (id) {
      // 弹框
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(id)
          .then((res) => {
            // console.log(res)
            if (res.data.meta.status === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              // 算出分页
              let pagesizeNew = Math.ceil(this.total - 1 / this.pagesize)
              this.pagenum = pagesizeNew < this.pagesize ? --this.pagenum : this.pagenum
              this.init()
            } else {
              this.$message({
                type: 'info',
                message: res.data.meta.msg
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改状态
    changeUserState (id, type) {
      // console.log(id, type)
      updateUserState(id, type)
        .then((res) => {
          // console.log(res)
          if (res.data.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取用户数据
    showGrandDialong (row) {
      // console.log(row)
      this.dialogFormVisibleUserRole = true
      this.grantForm.username = row.username
      this.grantForm.id = row.id
      // 实现下拉列表的数据展示
      this.grantForm.rid = row.rid
    },
    //  点击下拉框，获取角色id
    roleSelect (val) {
      // console.log(val)
      this.grantForm.rid = val
    },
    // 提交数据，新增
    addUserRole () {
      if (!this.grantForm.id) {
        this.$message({
          type: 'warning',
          message: '请选择用户'
        })
        return false
      } else {
        grantUserRole(this.grantForm.id, this.grantForm.rid)
          .then((res) => {
            // console.log(res)
            if (res.data.meta.status === 200) {
              this.dialogFormVisibleUserRole = false
              this.$message({
                type: 'success',
                message: res.data.meta.msg
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    // 编辑用户展示
    editUser (row) {
      this.editDialogFormVisible = true
      // console.log(row)
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editForm.id = row.id
    },
    // 编辑用户提交
    editUserSubmit () {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          editUser(this.editForm)
            .then((res) => {
              // console.log(res)
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                this.editDialogFormVisible = false
                this.init()
              } else {
                this.$message({
                  type: 'warning',
                  message: '用户输入不合法'
                })
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          this.$message({
            type: 'warning',
            message: '用户输入不合法'
          })
          return false
        }
      })
    }

  }
}
</script>

<style lang="less" scoped>
</style>
